<script setup>
import { registerUser } from '../http/user'
import { reactive, ref } from 'vue'

const ruleFormRef = ref()

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('Please input the password'))
  } else {
    if (ruleForm.checkPassword !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('checkPassword', () => null)
    }
    callback()
  }
}
const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入！'))
  } else if (value !== ruleForm.password) {
    callback(new Error('两次输入不匹配!'))
  } else {
    callback()
  }
}

const ruleForm = reactive({
  username: '',
  email: '',
  age: '',
  sex: '',
  password: '',
  checkPassword: '',
  userType: '1'
})

const rules = reactive({
  pass: [{ validator: validatePass, trigger: 'blur' }],
  checkPass: [{ validator: validatePass2, trigger: 'blur' }]
})

const submitForm = async (formEl) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      const rst = await registerUser(ruleForm)
      console.log(rst)
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<template>
  <div id="login-container">
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
  >
    <el-form-item label="用户名" prop="password">
      <el-input v-model="ruleForm.username" autocomplete="off" />
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="ruleForm.email" type="email" autocomplete="off" />
    </el-form-item>
    <el-form-item label="年龄" prop="age">
      <el-input v-model="ruleForm.age" type="number" autocomplete="off" />
    </el-form-item>
    <el-form-item label="性别" >
      <el-select v-model="ruleForm.sex" placeholder="请选择性别">
        <el-option label="男" value="1" />
        <el-option label="女" value="2" />
        <el-option label="未知" value="3" />
      </el-select>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
    </el-form-item>
    <el-form-item label="确认密码" prop="checkPassword">
      <el-input
        v-model="ruleForm.checkPassword"
        type="password"
        autocomplete="off"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
      >注册</el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
  </div>
</template>

<style scoped>

#login-container{
  width: 600px;
  height: 390px;
  background: #e5e9f2;
  position: absolute;
  left: 50%;
  top: 50%;
  padding-right: 60px;
  padding-top: 40px;
  transform: translate(-50%, -50%);
  border-radius: 5px;
}
</style>
